<template>
  <div class="coincertificate-list">
    <Row type="flex"
         justify="space-between"
         class="coincertificate-list-edit">
      <Col span="6">
      <Row type="flex"
           justify="start">
        <Col>
        <RadioGroup v-model="bottonActive"
                    @on-change="handleRadio"
                    class="from"
                    type="button"
                    size="large">
          <Radio :class="{ activeRadio: bottonActive === '兑换券统计' }"
                 label="兑换券统计"></Radio>
          <Radio :class="{ activeRadio: bottonActive === '套餐统计' }"
                 label="套餐统计"></Radio>
        </RadioGroup>
        </Col>
      </Row>
      </Col>
      <Col span="18">
      <Row type="flex"
           justify="end"
           class="code-row-bg">
        <Col>
        <Form class="from"
              :model="searchObj"
              label-position="left"
              inline>
          <FormItem :label-width="48">
            <div slot="label"
                 style="transform: translateX(12px);">时间：</div>
            <datePickerYmd @on-change="search"
                           :dateOption="dateOption"
                           :selectDateType.sync="selectDateType "
                           v-model="timeDate"></datePickerYmd>
          </FormItem>
          <!-- <FormItem :label-width="72">
                <div slot="label" style="transform: translateX(12px);">门店名称：</div>
                <Select
                  class="select-shop-item"
                  v-model="searchObj.shopIds"
                  multiple
                  filterable
                  @on-change="search"
                  :max-tag-count="1"
                  :max-tag-placeholder="maxTagPlaceholder"
                  style="width:180px"
                >
                  <Option
                    v-for="item in shopList"
                    :value="item.shopId"
                    :key="item.shopId"
                  >{{ item.shopName }}</Option>
                </Select>
              </FormItem> -->

          <!-- <FormItem :label-width="72">
                <div slot="label" style="transform: translateX(12px);">门店名称：</div>
                <vueTreeselectShop
                  :shopList.sync="searchObj.shopIds"
                  @id-change="search"
                  permissionCode="moms:report:coincouponanalytics"
                  v-model="testValue"
                ></vueTreeselectShop>
              </FormItem> -->

          <FormItem :label-width="72">
            <div slot="label"
                 style="transform: translateX(12px);">门店名称：</div>
            <!-- <vueTreeselectChoice
                 :multiple="true"
                 ref="vueTreeselectChoice"
                 @input="handleShop"
                 @on-api-finish="apiFinish"
                  permissionCode="moms:report:coincouponanalytics"
                  v-model="testValue"
                ></vueTreeselectChoice> -->
            <vueTreeselectChoice :max-tag-count='1'
                                 componentsType='iselect'
                                 :filterable="true"
                                 @on-change="handleShop"
                                 permissionCode="moms:report:coincouponanalytics"
                                 v-model="searchObj.shopIds"></vueTreeselectChoice>
          </FormItem>

          <FormItem>
            <Button type="primary"
                    class="coinrevenue-btn"
                    @click="search">查询</Button>
          </FormItem>
        </Form>
        </Col>
      </Row>
      </Col>
    </Row>

    <div class="gamecurrencyTable">
      <div class="gamecurrencyTable-cont">
        <el-table v-show="bottonActive === '兑换券统计'"
                  :summary-method="getSummaries"
                  border
                  show-summary
                  :row-class-name="tableRowClassName"
                  :header-row-class-name="tableHeaderRowClassName"
                  :header-cell-class-name="tableHeaderCellClassName"
                  :data="resData"
                  style="width: 100%;margin-bottom: 20px;border: 1px solid #dcdee2;"
                  row-key="rowKey"
                  default-expand-all
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column prop="couponName"
                           label="兑换券名称"
                           width="250">
            <template slot-scope="scope">
              <!-- <div> -->
              <!-- <span>{{scope.row}}</span> -->
              <span>{{scope.row.couponName}}</span>
              <!-- v-if="scope.row.pkgStatus === 2" -->
              <span v-if="scope.row.pkgStatus === 2"
                    class="table-delete">删除</span>
              <!-- </div> -->
            </template>
          </el-table-column>

          <el-table-column prop="convertCount"
                           label="兑换券张数"
                           width="180">
            <template slot-scope="scope">
              <!-- <span>{{scope.row}}</span>
              <span>test</span>-->
              <div :disabled="!scope.row.couponId"
                   :class="{ 'table-link': scope.row.couponId }"
                   class="table-link-button"
                   @click="handleGoDetai(scope.row, scope.columnIndex, scope)">
                <span class="convertCount">{{scope.row.convertCount}}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="convertCoinNum"
                           label="兑换游戏币数"></el-table-column>
          <el-table-column prop="convertCoinTotalNum"
                           label="小计"></el-table-column>
        </el-table>

        <el-table v-show="bottonActive === '套餐统计'"
                  border
                  :summary-method="getSummaries"
                  show-summary
                  :data="comboData"
                  :row-class-name="tableRowClassName"
                  :header-row-class-name="tableHeaderRowClassName"
                  :header-cell-class-name="tableHeaderCellClassName"
                  style="width: 100%;margin-bottom: 20px;border: 1px solid #dcdee2"
                  row-key="rowKey"
                  default-expand-all
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column prop="pkgName"
                           label="套餐名称"
                           width="250">
            <template slot-scope="scope">
              <!-- <div> -->
              <!-- <span>{{scope.row}}</span> -->
              <span>{{scope.row.pkgName}}</span>
              <!-- v-if="scope.row.pkgStatus === 2" -->
              <span v-if="scope.row.pkgStatus === 2"
                    class="table-delete">删除</span>
              <!-- </div> -->
            </template>
          </el-table-column>
          <el-table-column prop="pkgSalesCount"
                           label="消费数量"
                           width="180"></el-table-column>
          <el-table-column prop="pkgSalesCoinNum"
                           label="购币总数">
            <template slot-scope="scope">
              <div :disabled="!scope.row.pkgId"
                   :class="{ 'table-link': scope.row.pkgId }"
                   class="table-link-button"
                   @click="handleGoDetai(scope.row, scope.columnIndex, scope)">
                <span class="convertCount">{{scope.row.pkgSalesCoinNum}}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="pkgGiveCoinNum"
                           label="赠币总数"></el-table-column>
          <el-table-column prop="pkgSalesMoney"
                           label="消费总额">
            <template slot-scope="scope">
              <!-- <div> -->
              <!-- <span>{{scope.row}}</span> -->
              <span>{{scope.row.pkgSalesMoney | formatAmount}}</span>
              <!-- v-if="scope.row.pkgStatus === 2" -->

              <!-- </div> -->
            </template>
          </el-table-column>
        </el-table>

      </div>
    </div>
  </div>
</template>
<script>
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { shopCoincertificateQuery, shopcoincertificatePkg } from '@/api/report/shop'
import errorCaptured from '@/libs/errorCaptured'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import dayjs from 'dayjs'
import ZkTable from 'vue-table-with-tree-grid'
import { Table, TableColumn } from 'element-ui'
import { Decimal } from 'decimal.js'
import { formatAmount } from '@/libs/tools'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
export default {
  name: 'report_shop_coincertificate',
  components: { ZkTable, ElTable: Table, ElTableColumn: TableColumn, datePickerYmd, vueTreeselectChoice },
  data () {
    return {
      shopList: [],
      total: 0,
      isloading: false,
      bottonActive: '兑换券统计',
      bottonDateActive: '日',
      timeDate: [dayjs().format('YYYY-MM-DD 00:00:00'), dayjs().format('YYYY-MM-DD 00:00:00')],
      dateOption: {
        disabledDate (date) {
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      selectDateType: 'daterange',
      shopListTest: [],
      searchObj: {
        dateTimes: new Date(),
        dateRange: [new Date(), new Date()],
        pageSize: 10,
        shopIds: ''
      },

      data2: [],
      columns2: [
        {
          label: '兑换券名称',
          prop: 'couponName',
          minWidth: '200px',
          align: 'left',
          headerAlign: 'left',
          footerAlige: 'left'
        },
        {
          label: '兑换券张数',
          prop: 'convertCount',
          type: 'template',
          template: 'convertCount',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '兑换游戏币数',
          prop: 'convertCoinNum',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '小计',
          prop: 'convertCoinTotalNum',
          align: 'left',
          headerAlign: 'left'
          // type: 'template',
          // template: 'withdrawNum'
        }
      ],
      columns3: [
        {
          label: '套餐名称',
          prop: 'pkgName',
          type: 'template',
          template: 'pkgName',
          minWidth: '200px',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '消费数量',
          prop: 'pkgSalesCount',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '购币总数',
          prop: 'pkgSalesCoinNum',
          type: 'template',
          template: 'pkgSalesCoinNum',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '赠币总数',
          prop: 'pkgGiveCoinNum',
          align: 'left',
          headerAlign: 'left'
          // type: 'template',
          // template: 'pkgGiveCoinNum'
        },
        {
          label: '消费总额',
          prop: 'pkgSalesMoney',
          align: 'left',
          headerAlign: 'left'
          // type: 'template',
          // template: 'pkgSalesMoney'
        }
      ],

      resData: [], // 兑换券统计
      comboData: [] // 套餐统计
    }
  },
  computed: {
    tableCulumns () {
      if (this.bottonActive === '兑换券统计') return this.columns2
      return this.columns3
    },
    dateFormat () {
      if (this.bottonDateActive === '日') return 'yyyy-MM-dd'
      return 'yyyy-MM'
    },
    dateType () {
      if (this.bottonDateActive === '日') return 'date'
      return 'month'
    },
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      if (this.selectDateType === 'daterange') {
        return dayjs(this.timeDate[1])
          .add(1, 'day')
          .format('YYYY-MM-DD 00:00:00')
      }
      return this.timeDate[1]
    }
  },
  async created () {
    if (this.$store.state.user.orgType === 1) {
      this.searchObj.shopIds = this.$store.state.user.orgId
      this.search()
    }
    // 'e12ecec4-1ebb-4786-ad15-21e98604b966' ||

    // this.shopCoincertificateQuery()
  },
  mounted () {
  },
  methods: {
    // 门店改变
    async handleShop () {
      // const ids = await this.$refs.vueTreeselectChoice.getShopId()
      // this.searchObj.shopIds = ids
      this.search()
    },
    // apiFinish (isId) {
    //   if (isId) this.testValue = [this.$store.state.user.orgId]
    // },
    // 总计
    getSummaries (param) {
      const { columns, data } = param

      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          if (column.property === 'pkgSalesMoney') {
            sums[index] = formatAmount(sums[index].toFixed(2)) + ''
          } else {
            sums[index] += ''
          }
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },
    // 设置表格头部class
    tableHeaderRowClassName ({ row, rowIndex }) {
      return 'gray-header'
    },
    handleGoDetai (val, index, scope) {
      //  debugger
      if (!val.couponId && !val.pkgId) return
      let shopId = val.shopId
      this.$router.push({
        name: 'report_shop_coincertificate_detail',
        params: {
          id: val.couponId || val.pkgId,
          title: this.bottonActive,
          startDate: this.startDate,
          endDate: this.endDate,
          shopId
        }
      })
    },
    handleRadio (value) {
      this.search()
    },
    // 兑换券统计查询
    async shopCoincertificateQuery () {
      this.isloading = true
      let params = {
        merchantId: this.$store.state.user.merchantId,
        shopIds: [this.searchObj.shopIds],
        startDate: this.startDate,
        endDate: this.endDate
        // shopIds: ['e12ecec4-1ebb-4786-ad15-21e98604b966']
        // startDate: '2019-07-08',
        // endDate: '2019-07-09'
      }
      const [err, res] = await errorCaptured(shopCoincertificateQuery, params)

      this.isloading = false
      if (err) return null
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`) && (this.resData = [])

      let keys = this.columns2.map(item => item.prop)

      let data = (res.data.data || []).map((item, index) => {
        item.couponName = item.shopName
        item.children = item.coupons
        item.rowKey = item.shopId
        item.coupons &&
          item.coupons.forEach((element, k) => {
            element.rowKey = element.couponId
            element.shopId = item.shopId
            Object.keys(element).forEach(key => {
              if (keys.includes(key)) {
                if (key === 'couponName') {
                  item[key] = item.shopName
                } else {
                  item[key] = new Decimal(item[key] ? item[key] : 0).add(element[key] ? element[key] : 0).valueOf()
                }
              }
            })
          })
        return item
      })

      this.resData = data
    },
    // shopcoincertificatePkg 套餐统计查询
    async shopcoincertificatePkg (
      params = {
        merchantId: this.$store.state.user.merchantId,
        shopIds: [this.searchObj.shopIds],
        startDate: this.startDate,
        endDate: this.endDate
        // 'shopIds': ['e12ecec4-1ebb-4786-ad15-21e98604b966']
      }
    ) {
      this.isloading = true

      // try {
      const [err, res] = await errorCaptured(shopcoincertificatePkg, params)
      if (err) return null
      // const res = await shopcoincertificatePkg(params)

      this.isloading = false
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)

      let keys = this.columns3.map(list => {
        return list.prop
      })

      this.comboData = (res.data.data || []).map((item, index) => {
        item.children = item.pkgs
        item.pkgName = item.shopName
        item.rowKey = item.shopId
        // debugger
        // keys.map(keyItem => {
        //     item[keyItem] = 0
        // })
        item.pkgs &&
          item.pkgs.forEach((element, k) => {
            element.shopId = item.shopId
            element.rowKey = element.pkgId
            // element
            // element.pkgName = item.shopName
            Object.keys(element).forEach(key => {
              if (keys.includes(key)) {
                if (key === 'pkgName') {
                  item[key] = item.shopName
                } else {
                  item[key] = new Decimal(item[key] ? item[key] : 0).add(element[key]).valueOf()
                }
              }
            })
          })

        return item
      })
      // this.resData = [Object.assign({}, { shopName: data.shopName }, obj)]
      // } catch (error) {
      //   this.isloading = false
      //   this.$Message.error(`${error}`)
      // }
    },
    search () {
      if (!this.startDate) return this.$Message.error(`${'请选择时间'}`)
      if (!this.searchObj.shopIds) return this.$Message.error(`${'请选择门店'}`)
      if (this.bottonActive === '兑换券统计') return this.shopCoincertificateQuery()
      this.shopcoincertificatePkg()
      // this.shopCoincertificateQuery()
    }
  }
}
</script>
<style lang="less" scoped>
.coincertificate-list {
  min-width: 1015px;
  .from {
    margin-top: 24px;
  }

  .ivu-radio-group-button .ivu-radio-wrapper-checked {
    background: #2d8cf0;
    color: #fff;
  }
  .table-delete {
    padding: 5px;
    border-radius: 2px;
    background: #ed4014;
    font-size: 10px;
    color: #ffffff;
    letter-spacing: 0;
    text-align: justify;
  }
  .table-link-button {
    border: none;
    background: none;
    // color: #2d8cf0;
  }
  .table-link {
    width: 100%;
    height: 100%;
    font-size: 12px;
    letter-spacing: 0;
    span {
      color: #464c5b;
      border-bottom: 1px solid #fff;
      border-bottom-width: 0;
      color: #2d8cf0;
      cursor: pointer;
      color: #2d8cf0;
      border-bottom-width: 1px;
      border-bottom-color: #2d8cf0;
    }
  }
  .coincertificate-list-edit {
    padding-left: 20px;
  }
  .button_active {
    border: 1px solid #2d8cf0;
  }
  .gamecurrencyTable {
    background: #ffffff;
    padding: 40px 0;
    width: 100%;
    .gamecurrencyTable-cont {
      width: 70%;
      margin: auto;
    }
  }
}
</style>
<style lang="less">
.coincertificate-list {
  .select-shop-item {
    height: 35px;
    width: 210px;
    .ivu-select-selection {
      height: 35px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .ivu-tag {
      max-width: 100px;
    }
  }
  .gray-header {
    background-color: #f8f8f9;
    height: 40px;
    padding: 6px 0;
    font-weight: bold;
    color: #515a6e;
  }
  .table-row-color {
    background-color: #f8f8f9;
  }
}
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
